package com.cskaoyan.config;

import com.cskaoyan.realm.AdminRealm;
import com.cskaoyan.realm.WxRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.LinkedHashMap;


/**
 * @author Fantasylkh
 */
@Configuration
public class ShiroConfig {

    @Bean//开启aop
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }


    @Bean//shiro拦截器
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager manager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();

//        factoryBean.setLoginUrl("/login.jsp");

        factoryBean.setSecurityManager(manager);
        LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/admin/auth/**", "anon");
        filterMap.put("/wx/**", "anon");
        filterMap.put("/wx/auth/**", "anon");


        filterMap.put("/wx/**", "anon");
        filterMap.put("/wx/home/index", "anon");


        filterMap.put("/wx/order/**", "anon");
        filterMap.put("/login.jsp", "anon");
        filterMap.put("/wx/storage/fetch/**", "anon");
        filterMap.put("/admin/dashboard", "anon");



        filterMap.put("/**", "authc");

        factoryBean.setFilterChainDefinitionMap(filterMap);
        return factoryBean;
    }

    @Bean//安全控制器
    public DefaultWebSecurityManager securityManager(AdminRealm realm, LoginAuthenticator authenticator) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        securityManager.setSessionManager(webSessionManager());
        securityManager.setAuthenticator(authenticator);
        return securityManager;
    }

    @Bean
    public DefaultWebSessionManager webSessionManager() {

        return  new AdminSessionManager();
    }

    @Bean
    public LoginAuthenticator authenticator(AdminRealm adminRealm, WxRealm wxRealm) {
        LoginAuthenticator authenticator = new LoginAuthenticator();
        ArrayList<Realm> realms = new ArrayList<>();
        realms.add(adminRealm);
        realms.add(wxRealm);
        authenticator.setRealms(realms);
        return authenticator;
    }


}
